const express = require('express');
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const archiver = require('archiver');

const app = express();
const PORT = 8888;
const ROOT_DIR = '/Users/huah/Desktop/Share'; // 设置根目录

// 确保根目录存在
if (!fs.existsSync(ROOT_DIR)) {
  fs.mkdirSync(ROOT_DIR);
}

// 配置上传中间件
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const currentPath = req.body.path || '';
    const targetPath = path.join(ROOT_DIR, currentPath);
    cb(null, targetPath);
  },
  filename: (req, file, cb) => {
    // 添加文件名编码处理
    const decodedName = Buffer.from(file.originalname, 'latin1').toString('utf8');
    cb(null, decodedName);
  }
});
const upload = multer({ storage });

// 模板引擎设置
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// 中间件
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static('public'));
app.use('/share', express.static(ROOT_DIR));
// 首页路由
app.get('/', (req, res) => {
  const currentPath = req.query.path || '';
  const fullPath = path.join(ROOT_DIR, currentPath);

  if (!fs.existsSync(fullPath)) {
    return res.status(404).send('Directory not found');
  }

  fs.readdir(fullPath, { withFileTypes: true }, (err, items) => {
    if (err) return res.status(500).send(err);

    const directories = items.filter(item => item.isDirectory()).map(item => ({
      name: item.name,
      path: path.join(currentPath, item.name)
    }));

    const files = items.filter(item => item.isFile()).map(item => item.name);

    res.render('index', {
      currentPath,
      directories,
      files,
      parentPath: path.dirname(currentPath)
    });
  });
});

// 上传文件处理
app.post('/upload', upload.array('files'), (req, res) => {
  const currentPath = req.body.path || '';
  res.redirect(`/?path=${encodeURIComponent(currentPath)}`);
});
// 添加单个文件下载路由
app.get('/download/single', (req, res) => {
  const filePath = path.join(ROOT_DIR, req.query.path);

  // 安全验证
  if (!filePath.startsWith(ROOT_DIR)) {
    return res.status(403).send('Forbidden');
  }

  res.download(filePath, err => {
    if (err && !res.headersSent) {
      res.status(404).send('File not found');
    }
  });
});
// 下载文件处理
app.post('/download', (req, res) => {
  const files = req.body.files || [];
  const currentPath = req.body.path || '';

  const archive = archiver('zip');

  archive.on('error', (err) => {
    res.status(500).send(err);
  });

  res.attachment('download.zip');
  archive.pipe(res);

  files.forEach(file => {
    const filePath = path.join(ROOT_DIR, currentPath, file);
    if (fs.existsSync(filePath)) {
      archive.file(filePath, { name: file });
    }
  });
  archive.finalize();
});

// 在 index.js 中添加删除路由
app.post('/delete', (req, res) => {
  const files = JSON.parse(req.body.files || '[]');
  const currentPath = req.body.path || '';
  const fullPath = path.join(ROOT_DIR, currentPath);

  // 安全验证
  if (!validatePath(fullPath)) {
    return res.status(403).send('非法路径');
  }

  let errorFiles = [];

  files.forEach(file => {
    const filePath = path.join(fullPath, file);
    try {
      if (fs.existsSync(filePath)) {
        fs.rmSync(filePath, { force: true });
      }
    } catch (err) {
      errorFiles.push(file);
      console.error(`删除失败: ${filePath}`, err);
    }
  });

  if (errorFiles.length > 0) {
    return res.status(500).send(`以下文件删除失败: ${errorFiles.join(', ')}`);
  }
  res.send('删除成功');
  // res.redirect(`/?path=${encodeURIComponent(currentPath)}`);
});

// 路径验证函数 (添加到公共方法)
function validatePath(targetPath) {
  // const relative = path.relative(ROOT_DIR, targetPath);
  // return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
  return true;
}
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});